package com.youth.youthservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.youth.commonutils.BeanCopyUtils;
import com.youth.commonutils.R;
import com.youth.servicebase.exceptionhandler.GlobalException;
import com.youth.youthservice.entity.EduChapter;
import com.youth.youthservice.entity.EduCourse;
import com.youth.youthservice.entity.EduVideo;
import com.youth.youthservice.entity.chapter.ChapterVo;
import com.youth.youthservice.mapper.EduChapterMapper;
import com.youth.youthservice.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youth.youthservice.service.EduVideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author CM
 * @since 2023-5-1
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    private EduVideoService videoService;

    /*根据课程ID查询某一课程的章节*/
    @Override
    public  List<ChapterVo> getChapterByCourseId(String courseId) {
        LambdaQueryWrapper<EduChapter> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EduChapter::getCourseId,courseId).orderByAsc(EduChapter::getSort);
        List<EduChapter> list = list(queryWrapper);
        List<ChapterVo> res = BeanCopyUtils.copyBeanToList(list, ChapterVo.class);
        /*填充子科目*/
        res.stream().forEach(vo->vo.setChildren(
                videoService.GetVideoVoList(courseId,vo.getId())
        ));
        return res;
    }

    /*为课程添加章节，需要检查是否又重名*/
    @Override
    public R addChapter(EduChapter chapter) {
        /*检查当前课程中是否有重名章节*/
        LambdaQueryWrapper<EduChapter> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EduChapter::getCourseId,chapter.getCourseId())
                .eq(EduChapter::getTitle,chapter.getTitle());
        int count = count(queryWrapper);
        if(count != 0){
            throw new GlobalException(20003,"当前课程存在重复章节，请修改！");
        }
        /*保存新章节*/
        if(!save(chapter)){
            throw new GlobalException(20003,"课程章节添加失败");
        }
        return R.ok();
    }

    /*根据章节id删除课程对应章节，同时要删除其下的小节*/
    @Override
    @Transactional(rollbackFor = GlobalException.class)
    public R deleteById(String chapterId) {
        /*根据章节id删除对应小节*/
        videoService.deleteByChapterId(chapterId);
        /*先删章节*/
        if(!removeById(chapterId)){
            throw new GlobalException(20001,"章节删除失败!");
        }
        return R.ok();
    }
}
